# 使用多阶段构建
FROM node:18-alpine AS base

# 安装 pnpm
RUN npm install -g pnpm

# 设置工作目录
WORKDIR /app

# 复制 package.json 和 pnpm-lock.yaml（利用 Docker 缓存）
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY packages/server/package.json ./packages/server/
COPY packages/client/package.json ./packages/client/
COPY packages/types/package.json ./packages/types/

# 安装依赖（这层会被缓存，除非 package.json 改变）
RUN pnpm install --frozen-lockfile

# 复制源代码
COPY . .

# 构建阶段
FROM base AS builder

# 并行构建服务器和客户端
RUN pnpm build:server & pnpm build:client & wait

# 生产阶段
FROM node:18-alpine AS production

# 安装 pnpm
RUN npm install -g pnpm

# 创建非root用户
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nestjs -u 1001

# 设置工作目录
WORKDIR /app

# 复制 package.json 和 pnpm-lock.yaml
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY packages/server/package.json ./packages/server/
COPY packages/client/package.json ./packages/client/
COPY packages/types/package.json ./packages/types/

# 只安装生产依赖
RUN pnpm install --frozen-lockfile --prod

# 从构建阶段复制构建结果
COPY --from=builder /app/packages/server/dist ./packages/server/dist

# 创建上传目录
RUN mkdir -p packages/server/uploads/avatar

# 设置权限
RUN chown -R nestjs:nodejs /app
USER nestjs

# 设置环境变量
ENV NODE_OPTIONS="--experimental-global-webcrypto"

# 暴露端口
EXPOSE 3000

# 启动命令
CMD ["node", "--experimental-global-webcrypto", "packages/server/dist/main.js"] 